package hn.sigit.logic.queries.impl;

import hn.sigit.dao.hnd.administrative.HND_OperationPermitDAO;
import hn.sigit.logic.queries.OperationPermitQueryHelper;
import hn.sigit.logic.workflow.permits.OperationPermitHelper;
import hn.sigit.model.hnd.administrative.HND_OperationPermit;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

@Name(OperationPermitQueryHelper.NAME)
@Scope(value=ScopeType.CONVERSATION)
@AutoCreate
public class OperationPermitQueryHelperImpl extends QueryHelperImpl<HND_OperationPermit> implements OperationPermitQueryHelper, Serializable {
	private static final long serialVersionUID = 1L;
	
	
	@In
	private OperationPermitHelper operationPermitHelper;

	private HND_OperationPermit selected;
	

	@Override
	public List<HND_OperationPermit> getQueryResultList() {
		try {
			if (queryResultList == null && getSearchText() != null) {
				queryResultList = new ArrayList<HND_OperationPermit>();
				if (getSearchSelector().equals("0")) {
					//search by transaction presentation number
					HND_OperationPermit permit = HND_OperationPermitDAO.loadOperationPermitByID( Long.parseLong(getSearchText()) );
					if (permit != null)
						queryResultList.add( permit );
				}
			}
		}
		catch (Throwable t) {
			FacesContext.getCurrentInstance().addMessage(
					"",
					new FacesMessage(
							FacesMessage.SEVERITY_ERROR,
							t.getMessage(),
							""
					)
			);
			t.printStackTrace();
		}
		
		return queryResultList;
	}

	@Override
	public HND_OperationPermit getSelected() {
		if (selected == null) return null;
		
		return operationPermitHelper.getPermit();
	}

	@Override
	public void setSelected(HND_OperationPermit selected) {
		if (this.selected != selected) {
			this.selected = selected;
			operationPermitHelper.setPermit(selected);
		}
	}

	@Override
	public boolean isApproved() {
		return getSelected() != null &&
				getSelected().getApproved() != null &&
				getSelected().getApproved();
	}

	@Override
	public void destroy() {
	}
}
